package behavioralPattern.interpret.example01;

import java.util.Deque;
import java.util.LinkedList;

/**
 * 表达式解释器
 */
public class ExpressionInterpreter {

    // Deque双向队列
    private Deque<Long> deque = new LinkedList<>();

    // 接收表达式进行解析
    public long interpret(String expression) throws Exception {
        // 9 5 7 3 - + *
        String[] split = expression.split(" ");

        int length = split.length;

        // 获取数字
        for (int i = 0; i < (length + 1) /2 ; ++i) {
            // 数字添加到队列中
            deque.addLast(Long.parseLong(split[i]));
        }

        // 获取表达式中的符号
        for (int i = (length + 1) / 2 ; i < length; ++i){
            String operator = split[i];
            // 符号必须是 + - * /，否则异常
            boolean isValid = "+".equals(operator)
                                || "-".equals(operator)
                                || "*".equals(operator)
                                || "/".equals(operator);
            if (!isValid){
                throw new Exception("无效表达式！" + expression);
            }

            /// 获取集合中的数字
            Long num_1 = deque.pollFirst();
            Long num_2 = deque.pollFirst();

            long result = 0;
            if ("+".equals(operator)){
                result = num_1 + num_2;
            }else if ("-".equals(operator)){
                result = num_1 - num_2;
            }else if ("*".equals(operator)){
                result = num_1 * num_2;
            }else if ("/".equals(operator)){
                result = num_1 / num_2;
            }
            deque.addFirst(result);
        }

        // 注意：最终结果存储在集合中
        if (deque.size() != 1){
            throw new Exception("无效表达式！" + expression);
        }

        return deque.pop();
    }
}
